package com.commerceerp.system.service;

import com.commerceerp.system.entity.*;
import com.commerceerp.system.mapper.GoodMapper;
import com.commerceerp.system.mapper.OrderMapper;
import com.commerceerp.system.mapper.ShopMapper;
import com.commerceerp.system.util.ApiResult;
import com.commerceerp.system.util.DateUtil;
import com.commerceerp.system.util.HuilvUtil;
import com.commerceerp.system.util.StringUtils;
import com.ebay.sdk.*;
import com.ebay.services.client.ClientConfig;
import com.ebay.services.client.FindingServiceClientFactory;
import com.ebay.services.finding.FindingServicePortType;
import com.ebay.soap.eBLBaseComponents.*;
import com.google.common.collect.Lists;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Service
public class EbayService {

    @Value("${ebay.appID}")
    private String ebayAppID;

    @Value("${ebay.devID}")
    private String ebayDevID;

    @Value("${ebay.certID}")
    private String ebayCertID;

    @Value("${ebay.ruName}")
    private String ebayRuName;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private GoodMapper goodMapper;

    /**
     * 生成APIContext
     *
     * @return
     * @throws IOException
     */
    // Initializes ApiContext with token and eBay API server URL
    public ApiContext getApiContext(String token) {
        ApiContext apiContext = new ApiContext();
        ApiAccount apiAccount = new ApiAccount();
        apiAccount.setApplication(ebayAppID);
        apiAccount.setCertificate(ebayCertID);
        apiAccount.setDeveloper(ebayDevID);
        apiContext.getApiCredential().setApiAccount(apiAccount);
        ApiCredential cred = apiContext.getApiCredential();
        cred.seteBayToken(token);
        apiContext.setApiServerUrl("https://api.ebay.com/wsapi");
        apiContext.setEpsServerUrl("https://api.ebay.com/ws/api.dll");    // 这个要设置，不然会出错
        return apiContext;
    }

    //ebay店铺手动同步订单
    public ApiResult getEbayOrders(String id, String userId,String date,String date2) {
        List<ShopEbay> shopEbays = shopMapper.getShopEbayById(id, userId);
        if (shopEbays == null || shopEbays.size() == 0) {
            return new ApiResult(405, "没有店铺");
        }
        ClientConfig config = new ClientConfig();
        config.setApplicationId(ebayAppID);
        GetOrdersRequestType getOrdersRequestType = new GetOrdersRequestType();
        getOrdersRequestType.setSortingOrder(SortOrderCodeType.DESCENDING);
        getOrdersRequestType.setCreateTimeFrom(DateUtil.getCalendarToStringTime(date2));
        getOrdersRequestType.setCreateTimeTo(DateUtil.getCalendarToStringTime(date));
        for (ShopEbay shopEbay : shopEbays) {
            try {
                ApiCall apiCall = new ApiCall(getApiContext(shopEbay.getToken()));
                GetOrdersResponseType responseType = null;
                responseType = (GetOrdersResponseType) apiCall.execute(getOrdersRequestType);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置你想要的格式
                OrderType[] orders = responseType.getOrderArray().getOrder();
                for (OrderType o : orders) {
                    OrderVo orderInfo = new OrderVo();

                    orderInfo.setOrderStoreId(shopEbay.getId());
                    orderInfo.setShopUserId(shopEbay.getShopUserId());
                    orderInfo.setOrderChannel("1");

                    Calendar payTime = o.getPaidTime();
                    if(payTime != null){
                        try {
                            orderInfo.setOrderPayTime(df.format(payTime.getTime()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    orderInfo.setOrderBuyerId(o.getBuyerUserID());
                    orderInfo.setOrderMoney(o.getAmountPaid().getValue() + o.getAmountPaid().getCurrencyID().toString());
                    if(!StringUtils.equals(o.getAmountPaid().getCurrencyID().toString(),"USD")){
                        //兑换成人民币
                        orderInfo.setOrderMoneyCny(shopMapper.getMoneyUSD(o.getAmountPaid().getValue()+"",o.getAmountPaid().getCurrencyID().toString()));
                    }else{
                        orderInfo.setOrderMoneyCny(o.getAmountPaid().getValue()+"");
                    }
                    String ebayOrderId = o.getOrderID();
                    System.out.println(ebayOrderId);
                    orderInfo.setOrderId(ebayOrderId);
                    String orderStatus = o.getOrderStatus().value();
                    String status = "";
                    //1:待审核,2:待处理,3:待发货,4:发货成功,5:发货失败 6.完成 7.退款
                    if (StringUtils.equals(orderStatus, "PENDING")) {
                        status = "3";
                    } else if (StringUtils.equals(orderStatus, "Shipped")) {
                        status = "4";
                    } else if (StringUtils.equals(orderStatus, "Completed")) {
                        status = "7";
                    } else if (StringUtils.equals(orderStatus, "Cancelled")) {
                        status = "6";
                    } else if (StringUtils.equals(orderStatus, "Active")) {
                        status = "1";
                    }
                    orderInfo.setOrderStatus(status);
                    Calendar createdTime = o.getCreatedTime();
                    try {
                        String dateStr = df.format(createdTime.getTime());
                        orderInfo.setOrderDownTime(dateStr);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    orderInfo.setOrderBuyerId(o.getBuyerUserID());
                    orderInfo.setLeaveMessage(o.getBuyerCheckoutMessage());
                    AddressType shippingAddress = o.getShippingAddress();
                    if(shippingAddress != null){
                        orderInfo.setAddressRecipients(shippingAddress.getName());
                        orderInfo.setAddressPhone(shippingAddress.getPhone());
                        orderInfo.setAddressCity(shippingAddress.getCityName());
                        orderInfo.setAddressProvince(shippingAddress.getStateOrProvince());
                        orderInfo.setAddressCountry(shippingAddress.getCountryName());
                        orderInfo.setAddressLocationA(shippingAddress.getStreet1());
                        orderInfo.setAddressLocationB(shippingAddress.getStreet2());
                    }


                    //检索订单id
                    String orderId = orderMapper.getOrderIdId(ebayOrderId);
                    if (StringUtils.isEmpty(orderId)) {//新增订单
                        StringUtils.getOrderSerialNumber(orderInfo);
                        orderInfo.insert();
                        orderMapper.insert(orderInfo);

                        TransactionType[] list = o.getTransactionArray().getTransaction();
                        if (list != null && list.length > 0) {
                            List<OrderDetailVo> detailVos = Lists.newArrayList();
                            for(TransactionType item : list){
                                OrderDetailVo orderDetailVo = new OrderDetailVo();
                                GoodInfo goodInfo = new GoodInfo();
                                goodInfo.setGoodPlatformType("1");

                                ItemType itemType = item.getItem();
                                orderDetailVo.setOrderSku(itemType.getSKU());//sku
                                goodInfo.setGoodPlatformSku(itemType.getSKU());
                                orderDetailVo.setOrderGoodNumber(item.getQuantityPurchased());//数量
                                AmountType amountType = item.getTransactionPrice();
                                if(amountType != null){
                                    orderDetailVo.setOrderGoodPrice(item.getTransactionPrice().getValue() + item.getTransactionPrice().getCurrencyID().toString());//单价
                                    goodInfo.setGoodPurchasePrice(Double.valueOf(item.getTransactionPrice().getValue()));

                                }
                                orderDetailVo.setOrderGoodId(itemType.getItemID());//产品id
                                goodInfo.setGoodPlatformId(itemType.getItemID());

                                orderDetailVo.setOrderId(orderInfo.getId());
                                orderDetailVo.insert();

                                GetItemRequestType getItemRequestType = new GetItemRequestType();
                                getItemRequestType.setItemID(itemType.getItemID());
                                GetItemResponseType itemResponseType = null;
                                itemResponseType = (GetItemResponseType) apiCall.execute(getItemRequestType);
                                PictureDetailsType pictureDetailsType = itemResponseType.getItem().getPictureDetails();
                                if(pictureDetailsType != null){
                                    String url = pictureDetailsType.getPictureURL(0);
                                    orderDetailVo.setOrderImageUrl(url);
                                    goodInfo.setGoodPicPath(url);
                                }
                                goodInfo.setGoodUrl("https://www.ebay.com/itm/" + itemType.getItemID() + "?nordt=true");
                                goodInfo.setGoodPlatformName(itemResponseType.getItem().getTitle());
                                //根据平台商品id，获取本系统商品ID
                                String goodId = goodMapper.getGoodIdByPlatformId(goodInfo.getGoodPlatformId());
                                if(StringUtils.isEmpty(goodId)){
                                    goodInfo.setGoodId(StringUtils.getUUID());
                                    goodMapper.saveNewSystemGood(goodInfo);
                                }

                                detailVos.add(orderDetailVo);
                            }

                            orderMapper.insertOrderDetail(detailVos);
                        }

                    } else {//修改订单
                        orderInfo.setId(orderId);
                        orderMapper.update(orderInfo);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return new ApiResult(200, "同步订单结束");
    }

    /**
     * ebay添加商品
     * @param name 名称
     * @param description 简介
     * @param sku sku
     * @param pic 图片
     * @param price 单价
     * @param categoryId 分类
     * @param title 标题
     * @return
     */
    public ApiResult addItem(String id,String name,String description,String sku,String pic,double price,String categoryId,String title){
        ShopEbay shopEbay = shopMapper.getShopEbay(id);
        if(shopEbay == null){

            return new ApiResult(405,"店铺不合格");
        }
        AddItemRequestType addItemRequestType = new AddItemRequestType();
        ItemType item = new ItemType();
        item.setPartnerName(name);
        item.setDescription(description);
        item.setSKU(sku);
        PictureDetailsType pictureDetails = new PictureDetailsType();
        String[] pics = pic.split(",");
        pictureDetails.setExternalPictureURL(pics);
        pictureDetails.setPictureURL(pics);
        item.setPictureDetails(pictureDetails);
        AmountType amountType = new AmountType();
        amountType.setCurrencyID(CurrencyCodeType.USD);
        amountType.setValue(price);
        item.setStartPrice(amountType);
        item.setCurrency(CurrencyCodeType.USD);
        item.setCountry(CountryCodeType.US);
        item.setListingDuration("Days_5");
        item.setLocation(ListingTypeCodeType.CHINESE.value());
        CategoryType categoryType = new CategoryType();
        categoryType.setCategoryID(categoryId);
        item.setPrimaryCategory(categoryType);
        item.setTitle(title);
        item.setPaymentMethods(new BuyerPaymentMethodCodeType[]{BuyerPaymentMethodCodeType.AM_EX,BuyerPaymentMethodCodeType.PAY_PAL});
        item.setPayPalEmailAddress(shopEbay.getEmail());

        addItemRequestType.setItem(item);
        ApiCall apiCall = new ApiCall(getApiContext(shopEbay.getToken()));
        AddItemResponseType responseType = null;
        try {
            responseType = (AddItemResponseType) apiCall.execute(addItemRequestType);
            System.out.println("itemId:"+responseType.getItemID());
        } catch (SdkException e) {
            e.printStackTrace();
            return new ApiResult(405,"添加失败");
        }
        return new ApiResult(200,"添加成功");
    }

    //获取分类
    public ApiResult getCategory(String id){
        if(StringUtils.isEmpty(id)){
            id = "0";
        }
        return new ApiResult(goodMapper.getCategory(id));
    }

    //客服消息
    public ApiResult getMessage(String id, String userId,String date,String date2){
        List<ShopEbay> shopEbays = shopMapper.getShopEbayById(id, userId);
        if (shopEbays == null || shopEbays.size() == 0) {
            return new ApiResult(405, "没有店铺");
        }
        ClientConfig config = new ClientConfig();
        config.setApplicationId(ebayAppID);
        GetMemberMessagesRequestType getMemberMessagesRequestType = new GetMemberMessagesRequestType();
        getMemberMessagesRequestType.setMailMessageType(MessageTypeCodeType.ALL);
        getMemberMessagesRequestType.setStartCreationTime(DateUtil.getCalendarToStringTime(date));
        getMemberMessagesRequestType.setEndCreationTime(DateUtil.getCalendarToStringTime(date2));
        for (ShopEbay shopEbay : shopEbays) {
            try {
                ApiCall apiCall = new ApiCall(getApiContext(shopEbay.getToken()));
                GetMemberMessagesResponseType responseType = null;
                responseType = (GetMemberMessagesResponseType) apiCall.execute(getMemberMessagesRequestType);
                MemberMessageExchangeArrayType message = responseType.getMemberMessage();
                if(message != null){
                   MemberMessageExchangeType[] memberMessageExchanges =  message.getMemberMessageExchange();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置你想要的格式
                   for(MemberMessageExchangeType msg : memberMessageExchanges){
                       MemberMessageType question = msg.getQuestion();
                       SysTicket n = shopMapper.getSysTicket(question.getMessageID());
                       if(n != null){
                          continue;
                       }
                       SysTicket sysTicket = new SysTicket();

                       sysTicket.setShopStoreId(shopEbay.getId());
                       sysTicket.setUserId(shopEbay.getShopUserId());
                       sysTicket.setPlatformType("1");
                       String status = msg.getMessageStatus().value();
                       if("Unanswered".equals(status)){
                           sysTicket.setStatus("0");
                       }else{
                           sysTicket.setStatus("1");
                       }


                       sysTicket.setId(question.getMessageID());
                       Calendar addTime = msg.getCreationDate();
                       sysTicket.setAddTime(df.format(addTime.getTime()));//故障单创建的日期

                       Calendar updTime = msg.getLastModifiedDate();
                       sysTicket.setUpdTime(df.format(updTime.getTime()));//故障单上次更新的时间

                       String body = question.getBody();//标签
                       sysTicket.setBody(body);
                       String subject = question.getSubject();//主题
                       sysTicket.setSubject(subject);

                       //添加系统消息
                       shopMapper.saveSysTicket(sysTicket);
                   }
                }
                System.out.println(message);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return null;
    }

    public ApiResult huilv(){
        List<Huilv> list = shopMapper.getHuilvs();
        for(Huilv huilv:list){
            if(StringUtils.equals(huilv.getCode(),"USD")){
                continue;
            }
            JSONObject data = HuilvUtil.getRequest3(huilv.getCode(),"USD");
            if(data != null){
                huilv.setRate(new BigDecimal(data.getString("result")));
                huilv.setUpdTime(data.getString("updateTime"));
                shopMapper.updHuilv(huilv);
            }
        }
        return new ApiResult(200,"完成");
    }

}
